import { type NextRequest, NextResponse } from 'next/server';

export class UsersHandler {
    // Move users array to class level so it persists between requests
    private users = [
        {
            id: 1,
            name: 'Leanne Graham',
            username: 'Bret',
            email: 'Sincere@april.biz',
            phone: '1-770-736-8031 x56442',
            website: 'hildegard.org',
            address: {
                street: 'Kulas Light',
                city: 'Gwenborough'
            }
        },
        {
            id: 2,
            name: 'Ervin Howell',
            username: 'Antonette',
            email: 'Shanna@melissa.tv',
            phone: '010-692-6593 x09125',
            website: 'anastasia.net',
            address: {
                street: 'Victor Plains',
                city: 'Wisokyburgh'
            }
        }
    ];

    handle = async (request: NextRequest) => {
        const method = request.method.toUpperCase();
        
        if (method === 'GET') {
            // Simulate network delay
            await new Promise(resolve => setTimeout(resolve, 100));
            
            const { searchParams } = new URL(request.url);
            const id = searchParams.get('id');
            
            if (id) {
                const userId = parseInt(id, 10);
                const user = this.users.find(u => u.id === userId);
                if (user) {
                    return NextResponse.json([user]);
                } else {
                    return NextResponse.json([]);
                }
            } else {
                return NextResponse.json(this.users);
            }
        }
        
        if (method === 'POST') {
            try {
                const userData = await request.json();
                
                // Simulate network delay
                await new Promise(resolve => setTimeout(resolve, 100));
                
                const newUser = {
                    id: this.users.length + 1,
                    name: userData.name,
                    username: userData.name.toLowerCase().replace(' ', '_'),
                    email: userData.email,
                    phone: 'N/A',
                    website: 'example.com',
                    address: {
                        street: 'New Street',
                        city: 'New City'
                    }
                };
                
                this.users.push(newUser);
                return NextResponse.json(newUser, { status: 201 });
            } catch {
                return NextResponse.json({ error: 'Failed to create user' }, { status: 500 });
            }
        }
        
        return NextResponse.json({ error: 'Method not allowed' }, { status: 405 });
    };
}